package com.xuexiang.xuidemo.slice.imageview.edit;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.element.VectorElement;
import ohos.bundle.IBundleManager;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.multimodalinput.event.TouchEvent;
import ohos.utils.net.Uri;

import com.xuexiang.xui_lib.component.alpha.XUIAlphaImageButton;
import com.xuexiang.xui_lib.component.imageview.crop.CropDrawableUtils;
import com.xuexiang.xui_lib.component.imageview.edit.OnPhotoEditorListener;
import com.xuexiang.xui_lib.component.imageview.edit.PhotoEditor;
import com.xuexiang.xui_lib.component.imageview.edit.PhotoEditorView;
import com.xuexiang.xui_lib.component.imageview.edit.TextStyleBuilder;
import com.xuexiang.xui_lib.component.imageview.edit.ViewType;
import com.xuexiang.xui_lib.component.progress.loading.MiniLoadingDialog;
import com.xuexiang.xui_lib.util.DisplayUtils;
import com.xuexiang.xui_lib.util.ElementHelper;
import com.xuexiang.xuidemo.ResourceTable;
import com.xuexiang.xuidemo.util.FileUtils;
import com.xuexiang.xuidemo.util.XToastUtils;

import java.io.IOException;

public class PhotoEditSlice extends AbilitySlice implements Component.ClickedListener, OnPhotoEditorListener, Component.TouchEventListener {
    private static final int MY_PERMISSIONS_REQUEST_STORE = 100;

    /**
     * 选择系统图片Request Code
     */
    public static final int REQUEST_IMAGE = 112;
    private PhotoEditorView photoEditorView;
    private long saveStartTime;
    private PhotoEditor mPhotoEditor;
    private static final String[] storePermissions =
        {
            "ohos.permission.READ_USER_STORAGE",
            "ohos.permission.WRITE_USER_STORAGE"

        };
    private MiniLoadingDialog miniLoadingDialog;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_image_photo_edit_layout);
        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        photoEditorView = (PhotoEditorView) findComponentById(ResourceTable.Id_photo_editor_view);
        XUIAlphaImageButton ivUndo = (XUIAlphaImageButton) findComponentById(ResourceTable.Id_iv_undo);
        setComVector(ivUndo, ResourceTable.Graphic_ic_undo);
        setComVector((XUIAlphaImageButton) findComponentById(ResourceTable.Id_iv_redo), ResourceTable.Graphic_ic_redo);
        findComponentById(ResourceTable.Id_iv_undo).setTouchEventListener(this);
        findComponentById(ResourceTable.Id_iv_redo).setTouchEventListener(this);
        setClickListener(ResourceTable.Id_btn_select);
        setClickListener(ResourceTable.Id_btn_brush);
        setClickListener(ResourceTable.Id_btn_text);
        setClickListener(ResourceTable.Id_btn_rubber);
        setClickListener(ResourceTable.Id_btn_filter);
        setClickListener(ResourceTable.Id_btn_save);
        setClickListener(ResourceTable.Id_image_back);
        setClickListener(ResourceTable.Id_iv_undo);
        setClickListener(ResourceTable.Id_iv_redo);
        mPhotoEditor = new PhotoEditor.Builder(this, photoEditorView)
            .setPinchTextScalable(true)
            .build(); // build photo editor sdk
        mPhotoEditor.setOnPhotoEditorListener(this);
        try {
            miniLoadingDialog = new MiniLoadingDialog(this, "保存中...");
        } catch (NotExistException e) {
            e.printStackTrace();
        } catch (WrongTypeException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActive() {
        super.onActive();
    }

    private void setClickListener(int resId) {
        findComponentById(resId).setClickedListener(this);
    }

    private void setComVector(XUIAlphaImageButton img, int resId) {
        VectorElement vectorElement = new VectorElement(getContext(), resId);
        vectorElement.setAntiAlias(true);
        img.setImageElement(vectorElement);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_image_back:
                terminateAbility();
                break;
            case ResourceTable.Id_btn_select:
                selectPic();
                break;
            case ResourceTable.Id_iv_undo:
                mPhotoEditor.undo();
                break;
            case ResourceTable.Id_iv_redo:
                mPhotoEditor.redo();
                break;
            case ResourceTable.Id_btn_brush:
                mPhotoEditor.setBrushColor(ElementHelper.getColor(this, ResourceTable.Color_xui_config_color_white).getValue())
                    .setBrushSize(DisplayUtils.vp2px(this, 5))
                    .setBrushDrawingMode(true);
                break;
            case ResourceTable.Id_btn_text:
                final TextStyleBuilder styleBuilder = new TextStyleBuilder();
                styleBuilder.withTextColor(ElementHelper.getColor(this, ResourceTable.Color_xui_config_color_white).getValue());
                mPhotoEditor.addText("XUI", styleBuilder);
                break;
            case ResourceTable.Id_btn_rubber:
                mPhotoEditor.brushEraser();
                break;
            case ResourceTable.Id_btn_filter:
                break;
            case ResourceTable.Id_btn_save:
                saveImage();
                break;
        }
    }

    private void saveImage() {
        if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED
            || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED) {
            // 应用未被授予权限
            if (canRequestPermission("ohos.permission.READ_USER_STORAGE") || canRequestPermission("ohos.permission.WRITE_USER_STORAGE")) {
                // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                requestPermissionsFromUser(
                    storePermissions, MY_PERMISSIONS_REQUEST_STORE);
            }
        } else {
            // 权限已被授予
            if ((saveStartTime + 2000) <= System.currentTimeMillis()) {
                saveStartTime = System.currentTimeMillis();
                miniLoadingDialog.show();
                mPhotoEditor.saveAsFile(FileUtils.getImageSavePath(this), new PhotoEditor.OnSaveListener() {
                    @Override
                    public void onSuccess(String imagePath) {
                        miniLoadingDialog.hide();
                        if (photoEditorView != null) {
                            ImageSource imageSource = ImageSource.create(imagePath, null);
                            photoEditorView.getSource().setPixelMap(imageSource.createPixelmap(null));
                        }
                    }

                    @Override
                    public void onFailure(Exception exception) {
                        miniLoadingDialog.hide();
                        if (exception != null) {
                            exception.printStackTrace();
                            XToastUtils.error(exception);
                        }
                    }
                });
            }
        }

    }

    private void selectPic() {
        if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED
            || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED) {
            // 应用未被授予权限
            if (canRequestPermission("ohos.permission.READ_USER_STORAGE") || canRequestPermission("ohos.permission.WRITE_USER_STORAGE")) {
                // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                requestPermissionsFromUser(
                    storePermissions, MY_PERMISSIONS_REQUEST_STORE);
            }
        } else {
            Intent intent = new Intent();
            Operation opt = new Intent.OperationBuilder().withAction("android.intent.action.GET_CONTENT").build();
            intent.setOperation(opt);
            intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
            intent.setType("image/*");
            startAbilityForResult(intent, REQUEST_IMAGE);
        }
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent data) {
        super.onAbilityResult(requestCode, resultCode, data);
        //选择系统图片并解析
        if (requestCode == REQUEST_IMAGE) {
            if (data != null) {
                Uri uri = data.getUri();
                if (uri != null) {
                    mPhotoEditor.clearAllViews();
                    photoEditorView.getSource().setPixelMap(CropDrawableUtils.displayPixelMap(this, uri));
                }
            }
        }
    }

    @Override
    public void onEditTextChangeListener(Component rootView, String text, int colorCode) {
    }

    @Override
    public void onAddViewListener(ViewType viewType, int numberOfAddedViews) {
    }

    @Override
    public void onRemoveViewListener(ViewType viewType, int numberOfAddedViews) {
    }

    @Override
    public void onStartViewChangeListener(ViewType viewType) {
    }

    @Override
    public void onStopViewChangeListener(ViewType viewType) {
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        switch (component.getId()) {
            case ResourceTable.Id_iv_undo:
            case ResourceTable.Id_iv_redo:
                return true;
        }
        return false;
    }
}
